<template>
  <div class="home">
    <h1>管理员登录</h1>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="ruleForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-link href="/admin" type="primary">进入管理页面</el-link>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 15, message: '用户名长度必须在4到15个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 4, max: 15, message: '密码长度必须在4到15个字符', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          let url = 'http://localhost:8080/admins/login';
          console.log('url >>> ' + url);
          let data = 'username=' + this.ruleForm.username
              + '&password=' + this.ruleForm.password;
          // let data = {
          //   'username': this.ruleForm.username, // 'root'
          //   'password': this.ruleForm.password // '123456'
          // };
          console.log('data >>> ' + data);
          this.axios.post(url, data)
              .then((response) => {
                console.log(response);
                let json = response.data;
                let state = json.state;
                if (state == 200) {
                  console.log('管理员登录成功！');
                  console.log('管理员id：' + json.data.id);
                  console.log('管理员用户名：' + json.data.username);
                  console.log('管理员昵称：' + json.data.nickname);
                  console.log('管理员头像：' + json.data.avatar);
                  this.$message({
                    message: '管理员登录成功！',
                    type: 'success'
                  });
                } else {
                  console.log(json.message);
                  this.$message.error(json.message);
                }
              })
              .catch(function (error) {
                console.log(error);
              });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>